<!--
* description: 备件销售发票发送SAP
* author: ligy
* createdDate: 2021-3-2
-->
<template>
  <div class="app-container app-container-table">
    <el-col :span="12">
      <one-table-template
        ref="multipleTable"
        :key="oneTableKey"
        :dynamic-buttons="tableButtons"
        :dynamic-components="tableComponents"
        :dynamic-api-config="apiConfig"
        :dynamic-table-cols="tableCols"
        :dynamic-form-fields="formField"
        :dynamic-is-show-more-btn="true"
        :dynamic-is-show-select="true"
        :dynamic-is-init-table="true"
        :callback-obj="callbackObj"
      />
    </el-col>

    <el-col :span="12">
      <div :key="titleKey" class="filter-title table-title">
        <span class="left">网点名称：{{ item.dlrShortName }}</span>
        <span class="right">结算金额：{{ item.billAmount }}</span>
      </div>

      <mix-table
        ref="tableList"
        :is-dialog="true"
        :is-more="true"
        :is-paging="true"
        :dynamic-table-cols="dynamictableCols"
        :table-height="580"
      />
    </el-col>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import mixTable from '@/components/basicComponent/mixTable'
import Vue from 'vue'
import api from '@/api/pa/financialManagement'

export default {
  name: 'SparePartsSalesInvoiceSentToSAP',

  components: {
    mixTable,
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      titleKey: '1',
      item: {},
      selectData: {},
      apiConfig: api.queryInvoiceSendSapPage,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: '查询'
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'export',
          clickEvent: () => this.exportExcel(),
          text: '导出',
          position: 'left'
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'confirm',
          clickEvent: () => this.sendSAP(),
          text: '发送SAP'
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: '重置'
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/pa/dlrCode'),
              type: 'inputText',
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey2',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey3',
              labelName: '结算单号：',
              codeField: 'billOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey4',
              labelName: '结算日期：',
              codeField: 'startDate,endDate',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'daterange',
              isMul: false,
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey5',
              labelName: '发票号：',
              codeField: 'invoiceNo',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey6',
              labelName: '开票状态：',
              codeField: 'invoiceStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'invoiceStatus,invoiceStatusCn',
              options: [
                { invoiceStatus: '1', invoiceStatusCn: '已开票' },
                { invoiceStatus: '0', invoiceStatusCn: '未开票' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              span: 12
            }
          ],

      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'billOrderId',
              label: '结算单ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrCode',
              label: '网点编码',
              width: 140
            },
            {
              prop: 'dlrShortName',
              label: '网点名称',
              width: 120
            },
            {
              prop: 'billOrderCode',
              label: '结算单号',
              width: 140
            },
            {
              prop: 'billAmount',
              label: '结算金额'
            },
            {
              prop: 'billDate',
              label: '结算日期'
            },
            {
              prop: 'invoiceStatusCn',
              label: '开票状态'
            },
            {
              prop: 'invoiceCheckStatusCn',
              label: '发票复核状态'
            },
            {
              prop: 'invoiceSendFlagCn',
              label: '发票发送状态'
            },
            {
              prop: 'invoiceNo',
              label: '发票号'
            },
            {
              prop: 'invoiceDate',
              label: '开票日期'
            },
            {
              prop: 'invoiceAmount',
              label: '开票金额'
            },
            {
              prop: 'tax',
              label: '税额'
            },
            {
              prop: 'invoiceCode',
              label: '发票代码'
            }
          ],

      dynamictableCols: [
        {
          codeField: 'invoiceNo',
          label: '发票号',
          width: 140
        },
        {
          codeField: 'outCode',
          label: '出库单号',
          width: 140
        },
        {
          codeField: 'outDate',
          label: '出库日期',
          width: 140
        },
        {
          codeField: 'partNo',
          label: '备件编号',
          width: 140
        },
        {
          codeField: 'partName',
          label: '备件名称'
        },
        {
          codeField: 'outQty',
          label: '出库数量'
        },
        {
          codeField: 'billPrice',
          label: '结算单价'
        },
        {
          codeField: 'purPrice',
          label: '出库单价'
        },
        {
          codeField: 'discountPrice',
          label: '折扣'
        }
      ],

      formField: this.$utils.getFormField(this, {
        dlrCode: '',
        dlrShortName: '',
        billOrderCode: '',
        invoiceStatus: '',
        startDate: '',
        endDate: '',
        invoiceNo: '',
        billStatus: '',
        billOrderId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        },
        onRowDbClick: (selection) => {
          this.selectData = selection
          this.clickQuery()
        }
      }
    }
  },
  mounted() {
    this.queryTable(1)
  },

  methods: {
    // 发送SAP
    sendSAP() {
      console.log(this.selectData)
      const that = this
      const queryObj = {
        apiConfig: api.editInvoiceSendSapStatus,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // list: this.selectData.reduce((pre, cur, idx) => {
          //   const { billOrderId, updateControlId } = cur
          //   pre.push({ billOrderId, updateControlId })
          //   return pre
          // }, [])
          list:this.selectData
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    clickQuery() {
      const that = this
      this.item.dlrShortName = that.selectData.dlrShortName
      this.item.billAmount = that.selectData.billAmount
      this.titleKey += 1
      const queryObj = {
        apiConfig: api.queryInvoiceSendSapDetails,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          billOrderId: that.selectData.billOrderId
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.$refs.tableList.tableData = response.rows
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 导出
    exportExcel() {
      const fileName = this.$utils.fileNameWithTime('备件销售发票发送SAP.xlsx')
      this.$requestAPI({
        apiUrl: api.exportInvoiceSendSap.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.table-title{
  height: 30px;
  background-color: #fff;
}
.table-title span{
  display: block;
  width: 260px;
}
.table-title .left{
  float: left;
}
.table-title .right{
  float: right;
}
</style>
